package shm;

import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

import matlabcontrol.*;

public class MatlabOP {
	
	/**
	 * 
	 * @param cmd the Matlab command. Notice, the command must be at same directory as .jar.
	 * @param file the file to be opened.
	 */
	public static void callMatlab(String cmd, File file)  {
		MatlabProxyFactoryOptions options = new MatlabProxyFactoryOptions.Builder()
				.setUsePreviouslyControlledSession(true).setHidden(true)
				.build();

		MatlabProxyFactory factory = new MatlabProxyFactory(options);
		MatlabProxy proxy;
		
		try {
			proxy = factory.getProxy();
			
			String matlabCmd;
			matlabCmd = String.format("cd %s", file.getParent());
			System.out.println(matlabCmd);
			
			
			proxy.eval(matlabCmd);
			
			matlabCmd = String.format("%s('%s')", cmd, file);
			
			proxy.eval(matlabCmd);

			// Disconnect the proxy from MATLAB
			proxy.disconnect();
			
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	
	public static void selectFileAndCall(String cmd) {

		// select file.
		String lastPath = MainUI.pref.get("lastPath", "");
		JFileChooser fileopen = new JFileChooser(lastPath);
		fileopen.setMultiSelectionEnabled(false);
		FileNameExtensionFilter filter = new FileNameExtensionFilter(
				"All file", "txt");
		fileopen.addChoosableFileFilter(filter);
		int ret = fileopen.showDialog(null, "Open file");
		if (ret != JFileChooser.APPROVE_OPTION) {
			return ;
		}

		File fileSelected = fileopen.getSelectedFile();
		MainUI.pref.put("lastPath", fileSelected.getParent());
		
		MatlabOP.callMatlab(cmd, fileSelected);
		
	}

}
